package com.app.qbake.module.publish;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.app.qbake.R;
import com.app.qbake.base.bean.UploadPhoto;
import com.app.qbake.module.mine.event.EditGoodsSuccessEvent;
import com.app.qbake.module.mine.layout.EditGoodsLayout;
import com.app.qbake.module.publish.activity.VideoPreviewActivity;
import com.app.qbake.module.publish.activity.VideoUploadTipActivity;
import com.app.qbake.module.publish.di.PublishGoodsComponent;
import com.app.qbake.module.publish.event.VideoDelEvent;
import com.app.qbake.module.publish.event.VideoUploadedEvent;
import com.app.qbake.module.publish.layout.GoodsCategoryLayout;
import com.app.qbake.module.publish.layout.PhotoRecyclerView;
import com.app.qbake.module.publish.mvp.PublishGoodsView;
import com.app.qbake.module.publish.presenter.PublishGoodsPresenter;
import com.app.qbake.util.AppDialogHelper;
import com.wind.base.bean.Config;
import com.wind.base.mvp.view.DaggerMvpFragment;
import com.wind.base.repo.ConfigRepo;
import com.wind.base.utils.ActivityUtil;
import com.wind.coder.annotations.Api;
import com.wind.coder.annotations.Heros;
import com.wind.coder.annotations.Param;
import com.wind.data.mine.EditGoodsRequest;
import com.wind.data.mine.bean.EditGoodsInfo;
import com.wind.data.publish.PublishGoodsRequest;
import com.wind.data.publish.PublishGoodsResponse;
import com.wind.data.publish.bean.Category;
import com.wind.toastlib.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

@Heros(
        param = @Param(
                viewCanonicalName = "com.app.qbake.module.publish.mvp.PublishGoodsView",
                responseCanonicalName = "com.wind.data.publish.PublishGoodsResponse",
                requestCanonicalName = "com.wind.data.publish.PublishGoodsRequest"
        ),
        api = @Api(httpMethod = Api.HttpMethod.POST, url = "shop/create")
)
public class PublishGoodsFragment extends DaggerMvpFragment<PublishGoodsView, PublishGoodsPresenter, PublishGoodsComponent>
        implements PublishGoodsView, PhotoRecyclerView.UploadFileListener {

    public static final String ARGS_KEY_INFO = "args_key_info";
    @BindView(R.id.rv_pic)
    RecyclerView rv_pic;
    @BindView(R.id.ll_tuihuo)
    View ll_tuihuo;

    @BindView(R.id.tv_category)
    TextView tv_category;
    @Inject
    PublishGoodsPresenter presenter;
    PhotoRecyclerView mPhotoRecyclerView;

    GoodsCategoryLayout mGoodsCategoryLayout;

    @BindView(R.id.et_goods_desc)
    EditText et_goods_desc;

    @BindView(R.id.et_goods_price)
    EditText et_goods_price;

    @BindView(R.id.et_goods_num)
    EditText et_goods_num;
    @BindView(R.id.et_goods_postprice)
    EditText et_goods_postprice;

    @BindView(R.id.tv_video_content)
    TextView tv_video_content;

    EditGoodsLayout mEditGoodsLayout;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_publish_goods;
    }

    @Override
    public PublishGoodsPresenter createPresenter() {
        return presenter;
    }

    private EditGoodsInfo mEditGoodsInfo;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        mEditGoodsLayout = new EditGoodsLayout(getActivity());

        mEditGoodsInfo = (EditGoodsInfo) getArguments().getSerializable(ARGS_KEY_INFO);
        mPhotoRecyclerView = new PhotoRecyclerView(getActivity(), rv_pic);
        mPhotoRecyclerView.setUploadFileListener(this);
        mGoodsCategoryLayout = new GoodsCategoryLayout(getActivity(), tv_category);

        if (mEditGoodsInfo != null) {
            //获取商品全部信息

            inflateGoods();
        }
        Config config = ConfigRepo.getInstance().get(getActivity());
        String mode = config.getCur_mode();
        // if ("no".equals(mode)) {
        mHander.postDelayed(new Runnable() {
            @Override
            public void run() {

                if (getActivity() != null && !getActivity().isFinishing()) {
                    AppDialogHelper.showTipDialog(getActivity(), "宝贝图片及描述信息必须符合国家规定，不能含有非法，色情以及与宝贝无关的信息，若违规一经发现将封号处理。",
                            "同意", "不同意", new AppDialogHelper.DialogOperCallback() {

                                @Override
                                public void onDialogConfirmClick() {
                                    ActivityUtil.finish(getActivity());
                                }
                            });
                }
            }
        }, 500);
        //}

    }

    private Handler mHander = new Handler();

    private void inflateGoods() {
        final EditGoodsInfo goods = mEditGoodsInfo;
        List<UploadPhoto> photos = new ArrayList<>();
        for (String url : goods.getImages()) {
            photos.add(new UploadPhoto(url));
        }

        mPhotoRecyclerView.addItems(photos);
        et_goods_desc.setText(goods.getTitle());
        et_goods_price.setText(goods.getPrice());
        if (TextUtils.isEmpty(goods.getPostage_price())) {
            et_goods_postprice.setText("0");
        } else {
            et_goods_postprice.setText(goods.getPostage_price());
        }
        et_goods_num.setText(goods.getNumber() + "");
        tv_category.postDelayed(new Runnable() {
            @Override
            public void run() {
                Category category = mGoodsCategoryLayout.getCategoryById(goods.getCategory_id() + "");
                if (category != null) {
                    tv_category.setText(category.getZh_title());
                }
            }
        }, 1200);

        boolean isVideo = goods.getIs_video() == 1;
        if (isVideo) {
            mVideoPath = goods.getVideo_url();
            tv_video_content.setText("已上传");
        }
        boolean saleReturn = goods.getSales_return() == 1;
        if (saleReturn) {
            ll_tuihuo.setActivated(true);
        } else {
            ll_tuihuo.setActivated(false);
        }
    }

    @Override
    public void onSuccess(PublishGoodsResponse response) {
        ToastUtil.showToast(getActivity(), "发布成功");
        ActivityUtil.finish(getActivity());
    }

    private String mVideoPath;

    @OnClick({R.id.ll_tuihuo, R.id.rl_category, R.id.tv_publish, R.id.layout_video})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.layout_video:
                if (TextUtils.isEmpty(mVideoPath))
                    VideoUploadTipActivity.start(getActivity());
                else {
                    //视频预览
                    VideoPreviewActivity.start(getActivity(), mVideoPath);
                }
                break;
            case R.id.ll_tuihuo:
                ll_tuihuo.setActivated(!ll_tuihuo.isActivated());
                break;
            case R.id.rl_category:
                mGoodsCategoryLayout.showWheelLoc();
                break;
            case R.id.tv_publish:
                if (validate()) {
                    showOpLoadingIndicator();
                    mPhotoRecyclerView.uploadFile();
                }
                break;
        }
    }

    private void doPublish(List<String> urls) {
        PublishGoodsRequest publishGoodsRequest = buildPublishRequest(urls);
        if (mEditGoodsInfo != null) {
            EditGoodsRequest editGoodsRequest = buildEditGoodsRequest(publishGoodsRequest);

            mEditGoodsLayout.edit(editGoodsRequest);
        } else {
            presenter.execute(publishGoodsRequest);
        }

    }

    private EditGoodsRequest buildEditGoodsRequest(PublishGoodsRequest publishGoodsRequest) {
        EditGoodsRequest request = new EditGoodsRequest();
        request.setId(mEditGoodsInfo.getId());
        request.setTitle(publishGoodsRequest.getTitle());
        request.setCategory_id(publishGoodsRequest.getCategory_id());
        request.setPrice(publishGoodsRequest.getPrice());
        request.setPostage_price(publishGoodsRequest.getPostage_price());
        request.setVideo_url(publishGoodsRequest.getVideo_url());
        request.setNumber(publishGoodsRequest.getNumber());
        request.setImage_url(publishGoodsRequest.getImage_url());
        request.setSales_return(publishGoodsRequest.getSales_return());
        request.setIs_video(publishGoodsRequest.getIs_video());
        return request;
    }

    private PublishGoodsRequest buildPublishRequest(List<String> urls) {
        PublishGoodsRequest request = new PublishGoodsRequest();

        String desc = getText(et_goods_desc);
        String price = getText(et_goods_price);
        String num = getText(et_goods_num);
        String categoryName = getText(tv_category);

        request.setTitle(desc);
        Category category = mGoodsCategoryLayout.getCategory(categoryName);
        if (category != null)
            request.setCategory_id(category.getId());
        request.setPrice(price);

        request.setPostage_price(getText(et_goods_postprice));
        if (TextUtils.isEmpty(mVideoPath)) {
            request.setVideo_url("");
            request.setIs_video(0);
        } else {
            request.setVideo_url(mVideoPath);
            request.setIs_video(1);
        }
        request.setNumber(Integer.parseInt(num));
        StringBuilder urlsBuilder = new StringBuilder("[");
        for (String url : urls) {
            urlsBuilder
                    .append("\"")
                    .append(url)
                    .append("\"")
                    .append(",");
        }
        urlsBuilder.deleteCharAt(urlsBuilder.length() - 1);
        urlsBuilder.append("]");
        //LogUtil.e("image_url",urlsBuilder.toString());
        request.setImage_url(urlsBuilder.toString());
        if (ll_tuihuo.isActivated()) {
            request.setSales_return(1);
        } else {
            request.setSales_return(0);
        }

        return request;

    }

    private boolean validate() {
        String desc = et_goods_desc.getText().toString().trim();
        if (desc.length() < 5) {
            ToastUtil.showToast(getActivity(), "商品描述最少5个字");
            return false;
        }

        boolean photo = mPhotoRecyclerView.validate("至少上传一张照片");
        if (photo) {
            String price = getText(et_goods_price);
            if (TextUtils.isEmpty(price)) {
                ToastUtil.showToast(getActivity(), "请输入价格");
                return false;
            }

            String num = getText(et_goods_num);
            if (TextUtils.isEmpty(num) || "0".equals(num)) {
                ToastUtil.showToast(getActivity(), "请输入数量");
                return false;
            }
            String category = getText(tv_category);
            if (TextUtils.isEmpty(category)) {
                ToastUtil.showToast(getActivity(), "请选择分类");
                return false;
            }
        }
        return true;
    }


    @Override
    public void onUploadError() {
        hideOpLoadingIndicator();
    }

    @Override
    public void onUploadFileProgress() {

    }

    @Override
    public void onUploadFileSuccess(List<String> urls) {
        doPublish(urls);
    }


    @Subscribe
    public void onVideoDelEvent(VideoDelEvent event) {
        mVideoPath = "";
        tv_video_content.setText("");
    }

    @Subscribe
    public void onVideoUploadedEvent(VideoUploadedEvent event) {
        mVideoPath = event.getVideoUrl();
        tv_video_content.setText("已上传");
    }


    /**
     * 编辑商品成功
     *
     * @param event
     */
    @Subscribe
    public void onEditGoodsSuccessEvent(EditGoodsSuccessEvent event) {
        ToastUtil.showToast(getActivity(), "编辑成功");
        ActivityUtil.finish(getActivity());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }


    public static Fragment getInstance(EditGoodsInfo goods) {

        PublishGoodsFragment f = new PublishGoodsFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARGS_KEY_INFO, goods);
        f.setArguments(args);
        return f;
    }


}
